<template>
  <div class="container">
    <el-card class="search-container">
      <el-form
        :model="searchForm"
        size="mini"
        :inline="true"
        label-suffix="："
        ref="searchForm"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="searchForm.name" clearable></el-input>
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-select v-model="searchForm.status" clearable placeholder="请选择">
            <el-option
              v-for="(item, index) in statusList"
              :key="`status_${index}`"
              :label="item"
              :value="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品类型" prop="type">
          <el-select v-model="searchForm.type" clearable placeholder="请选择">
            <el-option
              v-for="(item, index) in typeList"
              :key="`type_${index}`"
              :label="item"
              :value="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="商品类型" prop="type">
          <el-select v-model="searchForm.type" clearable placeholder="请选择">
            <el-option
              v-for="(item, index) in typeList"
              :key="`type_${index}`"
              :label="item"
              :value="index"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" @click="searchHandle">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="container-result">
      <thy-caption title="查询结果" margin>
        <el-button
          type="primary clerafix"
          @click="addHandle"
          style="float: right;"
          size="mini"
          >新建商品</el-button
        >
      </thy-caption>
      <el-table size="small" stripe border :data="list" v-loading="loading">
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column
          prop="name"
          label="商品名称"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="desc"
          label="商品描述"
          width="200"
        ></el-table-column>
        <el-table-column prop="pic" label="封面" width="140">
          <template slot-scope="scope">
            <img :src="scope.row.pic" alt width="120" />
          </template>
        </el-table-column>
        <!-- <el-table-column prop="banners" label="轮播图" width="270">
          <template slot-scope="scope">
            <img
              v-for="(item, index) in JSON.parse(scope.row.banners)"
              :key="`banner_${index}`"
              :src="item.pic"
              alt=""
              width="120"
            />
          </template>
        </el-table-column>-->
        <el-table-column
          prop="sale"
          label="原价(￥)"
          :formatter="prictFormat"
        ></el-table-column>
        <el-table-column
          prop="price"
          label="现价(￥)"
          :formatter="prictFormat"
        ></el-table-column>
        <el-table-column prop="status" label="类型">
          <template slot-scope="scope">
            <span>{{ typeList[scope.row.type] || '其它' }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="properties" label="规格"></el-table-column> -->
        <el-table-column
          prop="end"
          label="结束日期"
          width="180"
        ></el-table-column>
        <el-table-column prop="size" label="库存"></el-table-column>
        <el-table-column prop="number" label="已售"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <span>{{ scope.row.status ? '下架' : '上架' }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="editHandle(scope.$index)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        @current-change="paginationHandle"
        :current-page="page"
        :total="total"
      ></el-pagination>
    </el-card>

    <el-dialog title="新建商品" :visible.sync="dialogVisible" width="70%">
      <el-form
        v-if="dialogVisible"
        :model="form"
        size="mini"
        label-width="120px"
        label-suffix="："
        ref="form"
      >
        <el-form-item label="商品名称" prop="name" required>
          <el-input v-model="form.name" clearable></el-input>
        </el-form-item>
        <el-form-item label="商品描述" prop="desc" required>
          <el-input v-model="form.desc" clearable></el-input>
        </el-form-item>
        <el-form-item label="原价(￥)" prop="sale" required>
          <el-input v-model="form.sale" clearable></el-input>
        </el-form-item>
        <el-form-item label="现价(￥)" prop="price" required>
          <el-input v-model="form.price" clearable></el-input>
        </el-form-item>
        <el-form-item label="商家名称" prop="remark.shop.name" required>
          <el-input v-model="form.remark.shop.name" clearable></el-input>
        </el-form-item>
        <el-form-item label="商家地址" prop="remark.shop.address" required>
          <el-input v-model="form.remark.shop.address" clearable></el-input>
        </el-form-item>
        <el-form-item label="商家详情" prop="remark.shop.detail" required>
          <el-input v-model="form.remark.shop.detail" clearable></el-input>
        </el-form-item>
        <el-form-item label="商品类型" prop="type" required>
          <el-select v-model="form.type" :disabled="disabled">
            <el-option
              v-for="(item, index) in typeList"
              :key="`status_${index}`"
              :label="item"
              :value="index"
            />
          </el-select>
        </el-form-item>
        <template v-if="form.type === 1">
          <el-form-item label="券码类型" prop="subtype" required>
            <el-select v-model="form.subtype">
              <el-option
                v-for="(item, index) in subTypeList"
                :key="`subTypeList_${index}`"
                :label="item"
                :value="index"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="可预约日期" prop="subtype" required>
            <el-date-picker
              v-model="form.remark.date"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </template>

        <el-form-item label="结束日期" prop="end" required>
          <el-date-picker
            v-model="form.end"
            type="datetime"
            placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="库存" prop="size" required>
          <el-input
            v-model="form.size"
            clearable
            :disabled="form.type === 2"
          ></el-input>
        </el-form-item>
        <el-form-item label="已售" prop="number" required>
          <el-input v-model="form.number" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="number" required>
          <el-select v-model="form.status" :disabled="form.type > 9999">
            <el-option
              v-for="(item, index) in statusList"
              :key="`type_${index}`"
              :label="item"
              :value="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="封面图" prop="pic" required>
          <thy-upload v-model="form.pic"></thy-upload>
        </el-form-item>
        <el-form-item label="轮播图">
          <div class="banner-img-container">
            <div
              v-for="(item, idx) in form.banners"
              :key="`pic_${idx}`"
              class="pic-item"
            >
              <img :src="item.pic" height="100" alt />
              <div class="pic-opertion">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deletePicHandle(idx)"
                ></el-button>
              </div>
            </div>
          </div>
          <thy-upload
            @on-upload="addPicHandle"
            :showList="false"
            :limit="100"
          ></thy-upload>
        </el-form-item>
        <el-form-item label="商品详情" prop="detail">
          <vue-editor
            id="editor"
            v-model="form.detail"
            @imageAdded="handleImageAdded"
            useCustomImageHandler
          ></vue-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="submitForm"
          >确定</el-button
        >
        <el-button size="mini" @click="resetForm">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import deepClean from 'deep-clean';
import { VueEditor } from 'vue2-editor';
export default {
  name: 'flash-goods',
  components: {
    VueEditor
  },
  data() {
    return {
      disabled: false,
      loading: true,
      dialogVisible: false,
      list: [],
      total: 0,
      page: 1,
      form: {},
      searchForm: {},
      typeList: ['邮寄', '人工预约', '券码'],
      statusList: ['上架', '下架'],
      subTypeList: ['非餐券', '餐券']
    };
  },
  methods: {
    prictFormat(row, column, cellValue) {
      return cellValue / 100;
    },
    searchHandle() {
      this.$refs.searchForm.validate(valid => {
        if (valid) {
          this.getData();
        }
      });
    },
    paginationHandle(page) {
      this.getData(page);
    },
    getData(page = 1) {
      this.loading = true;
      this.$request
        .get('/admin/flash/goods/list', {
          params: deepClean({
            page,
            pageSize: 10,
            ...this.searchForm
          })
        })
        .then(data => {
          this.page = page;
          this.list = data.rows.filter(item => item.type < 10000);
          this.total = data.count;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleImageAdded: function(file, Editor, cursorLocation, resetUploader) {
      this.$message.info('正在上传...');
      var formData = new FormData();
      formData.append('file', file);
      if (file.size > 5000000) {
        this.$message.error('文件过大，请重新上传');
        return;
      }
      this.$request
        .post('/admin/upload/pic', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        .then(data => {
          this.$message.success('上传成功.');
          Editor.insertEmbed(cursorLocation, 'image', data.url);
          resetUploader();
        });
    },
    addHandle() {
      this.disabled = false;
      this.form = {
        size: 0,
        number: 0,
        status: 0,
        subtype: 0,
        banners: [],
        remark: {
          date: [],
          shop: {
            name: null,
            address: null,
            detail: null
          }
        }
      };
      this.dialogVisible = true;
    },
    editHandle(idx) {
      this.disabled = true;
      const item = JSON.parse(JSON.stringify(this.list[idx]));
      item.banners = JSON.parse(item.banners || '[]');
      item.remark = JSON.parse(item.remark || '{}');
      if (!item.remark.shop) {
        item.remark.shop = {
          name: null,
          address: null,
          detail: null
        };
      }
      item.price = item.price / 100;
      item.sale = item.sale / 100;
      this.form = item;
      this.dialogVisible = true;
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          let url = '/admin/flash/goods/add';
          if (this.form.id) {
            delete this.form.created_at;
            delete this.form.updated_at;
            url = '/admin/flash/goods/update';
          }
          const params = JSON.parse(JSON.stringify(this.form));
          params.price = params.price * 100;
          params.sale = params.sale * 100;
          this.$request.post(url, params).then(() => {
            this.$message.success('成功');
            this.dialogVisible = false;
            this.getData(this.page);
          });
        }
      });
    },
    resetForm() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
    },
    addPicHandle(url) {
      this.form.banners.push({
        pic: url
      });
    },
    deletePicHandle(idx) {
      this.form.banners.splice(idx, 1);
    }
  },
  mounted() {
    this.getData();
  }
};
</script>

<style lang="less">
.banner-img-container {
  display: inline-block;
  .pic-item {
    margin-right: 10px;
    position: relative;
    display: flex;
    align-items: center;
    border: 1px solid #ccc;
    border-radius: 3px;
    float: left;
  }
  .pic-opertion {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
